package com.ayf.payment.game.api.controller.player;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.ayf.payment.game.api.cache.redis.RedisCacheUtil;
import com.ayf.payment.game.api.dto.player.*;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.type.CommonConstants;
import com.ayf.payment.game.api.utils.CommonResult;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.ayf.payment.integral.dto.IntegralDTO;
import com.ayf.payment.integral.dto.*;
import com.ayf.payment.integral.exception.IntegralInfoException;
import com.ayf.payment.integral.service.remote.IntegralRemoteService;
import com.ayf.payment.integral.vo.IntegralVO;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zh-liang
 * @Date : 2020-08-19 18:22
 */
@RestController
public class PlayerIntegralController {

    private static final String PLATFORM_CODE = System.getenv("GAME_AYFPAY_PLATFORM_CODE");

    @Reference(version = "1.0.0",check = false)
    private IntegralRemoteService integralRemoteService;
    @Resource
    private RedisCacheUtil redisCacheUtil;
    @Resource
    private PlayerApi playerApi;

    /**
     * 发送短信
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/p/sms")
    public CommonResult<Map<String, Object>> sms(@RequestBody VerifyCodeVO vo) {
        if (StrUtil.isEmpty(vo.getPhone())) {
            throw new ParameterException("手机号不能为空");
        }
        if (!Validator.isMobile(vo.getPhone())) {
            throw new ParameterException("手机号格式错误");
        }
        if (StrUtil.isEmpty(vo.getSmsType())) {
            throw new ParameterException("短信类型不能为空");
        }
        if (playerApi.sendSms(vo.getPhone(), vo.getSmsType())) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "发送成功");
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "发送失败");
    }

    /**
     * 短信登录
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/p/login")
    public CommonResult<Map<String, Object>> login(@RequestBody PlayerLoginVO vo) {
        if (StrUtil.isEmpty(vo.getPhone())) {
            throw new ParameterException("手机号不能为空");
        }
        if (!Validator.isMobile(vo.getPhone())) {
            throw new ParameterException("手机号格式错误");
        }
        if (StrUtil.isEmpty(vo.getCode())) {
            throw new ParameterException("短信验证码不能为空");
        }
        if (vo.getGmId() == null) {
            throw new ParameterException("gmId不能为空");
        }
        String cache = redisCacheUtil.getObjectFromCache(PlayerKeyUtil.getSmsKey("LOGIN", vo.getPhone()));
        if (!vo.getCode().equals(cache)) {
            throw new ParameterException("短信验证码错误");
        }
        try {
            PlayerInfoApiDTO playerInfo = playerApi.getPlayerInfo(vo.getPhone());
            if (playerInfo == null) {
                throw new ParameterException("登录失败，请重新登录");
            }
            redisCacheUtil.delete(PlayerKeyUtil.getSmsKey("LOGIN", vo.getPhone()));
            return myLogin(vo, playerInfo.getId());
        } catch (IntegralInfoException e) {
            if (e.getCode() == 201) {
                PlayerInfoApiDTO playerInfoApiDTO = playerApi.loginRegister(vo.getPhone(), vo.getGmId());
                return myLogin(vo, playerInfoApiDTO.getId());
            }
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "登录失败");
    }

    private CommonResult<Map<String, Object>> myLogin(PlayerLoginVO vo, Long playerId) {
        String token = PlayerKeyUtil.getLoginToken();
        PlayerLoginToken playerLoginToken = new PlayerLoginToken();
        playerLoginToken.setPlatformCode(PLATFORM_CODE);
        playerLoginToken.setPhone(vo.getPhone());
        playerLoginToken.setGmId(vo.getGmId());
        playerLoginToken.setPlayerId(playerId);
        redisCacheUtil.setObjectToCache(token, playerLoginToken, 48L, TimeUnit.HOURS);
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", token);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "登录成功", map);
    }

    /**
     * 获取积分余额
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/p/getIntegralVal")
    public CommonResult<Long> getIntegralVal(PlayerLoginToken token) {
        String uniqueId = SnowFlakeUtils.getUniqueId();
        try {
            IntegralDTO integralDTO = new IntegralDTO();
            integralDTO.setPlatformCode(PLATFORM_CODE);
            integralDTO.setGmId(token.getGmId());
            integralDTO.setPlayerId(token.getPlayerId());
            Long val=0L;
            if(integralRemoteService != null){
                IntegralInfoDTO integralInfo = integralRemoteService.getIntegralInfo(integralDTO);
                val = integralInfo.getVal();
            }
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "获取成功",val );
        } catch (IntegralInfoException e) {
            if (e.getCode() == -1) {
                LogPortal.error("[{}]获取积分余额失败，错误信息:[{}]", uniqueId, e.getMsg());
            }
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "错误码" + uniqueId);
    }

    /**
     * 积分记录查询
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/p/integralLogList")
    public CommonResult<MyPageDTO<IntegralLogDTO>> integralLogList(PlayerLoginToken token, @RequestBody IntegralVO vo) {
        String uniqueId = SnowFlakeUtils.getUniqueId();
        try {
            vo.setPlatformCode(PLATFORM_CODE);
            vo.setGmId(token.getGmId());
            vo.setPlayerId(token.getPlayerId());
            if(integralRemoteService !=null){
                MyPageDTO<IntegralLogDTO> myPageDTO = integralRemoteService.integralLogList(vo);
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "积分记录查询成功", myPageDTO);
            } else {
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "积分记录查询成功",null);
            }
        } catch (IntegralInfoException e) {
            if (e.getCode() == -1) {
                LogPortal.error("[{}]积分记录查询失败，错误信息:[{}]", uniqueId, e.getMsg());
            }
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "错误码" + uniqueId);
    }

    /**
     * 商品兑换
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/p/exchange")
    public CommonResult<?> exchange(PlayerLoginToken token, @RequestBody IntegralDTO dto) {
        if (dto.getVal() == null) {
            throw new ParameterException("所需积分不能为空");
        }
        if (dto.getVal() <= 0) {
            throw new ParameterException("所需积分必须大于0");
        }
        if (StrUtil.isEmpty(dto.getRemark())) {
            throw new ParameterException("商品描述不能为空");
        }
        String uniqueId = SnowFlakeUtils.getUniqueId();
        try {
            IntegralDTO integralDTO = new IntegralDTO();
            integralDTO.setPlatformCode(PLATFORM_CODE);
            integralDTO.setGmId(token.getGmId());
            integralDTO.setPlayerId(token.getPlayerId());
            IntegralInfoDTO integralInfo = integralRemoteService.getIntegralInfo(integralDTO);
            if (integralInfo.getVal() < dto.getVal()) {
                throw new ParameterException("积分不足");
            }
            dto.setPlatformCode(PLATFORM_CODE);
            dto.setGmId(token.getGmId());
            dto.setPlayerId(token.getPlayerId());
            integralRemoteService.addOrder(dto);
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "商品兑换成功");
        } catch (IntegralInfoException e) {
            if (e.getCode() == -1) {
                LogPortal.error("[{}]商品兑换失败，错误信息:[{}]", uniqueId, e.getMsg());
            }
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "错误码" + uniqueId);
    }

    /**
     * 兑换订单查询
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/p/playerOrderList")
    public CommonResult<MyPageDTO<IntegralExchangeOrderDTO>> playerOrderList(PlayerLoginToken token, @RequestBody IntegralVO vo) {
        String uniqueId = SnowFlakeUtils.getUniqueId();
        try {
            vo.setPlatformCode(PLATFORM_CODE);
            vo.setGmId(token.getGmId());
            vo.setPlayerId(token.getPlayerId());
            if(integralRemoteService !=null){
                MyPageDTO<IntegralExchangeOrderDTO> myPageDTO = integralRemoteService.integralOrderList(vo);
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "兑换订单查询成功", myPageDTO);
            } else {
                return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "兑换订单查询成功",null);
            }
        } catch (IntegralInfoException e) {
            if (e.getCode() == -1) {
                LogPortal.error("[{}]兑换订单查询失败，错误信息:[{}]", uniqueId, e.getMsg());
            }
        }
        return new CommonResult<>(CommonConstants.RETURN_ERROR, "错误码" + uniqueId);
    }
}
